package org.devcp.tp.common.event.dispatch;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.devcp.tp.common.event.SysEvent;
import org.devcp.tp.common.event.SysEventRegister;
import org.devcp.tp.common.event.util.SysEventUtil;
import org.jweb.common.activeMQ.listener.MsgListener;

/**
 * 从activeMQ消息队列读取系统事件并通过事件派发线程将事件派发出去
 * @author Administrator
 *
 */

public class WebsocketActiveMQEventDispatch implements MessageListener {
	private static Log log = LogFactory.getLog(MsgListener.class);
	
	/**
	 * 全局事件注册表，现在只能在单节点上使用，无法存放到ehcache服务器，因为spring websocketSession不能被序列化
	 */
	public static List<Map<String,SysEventRegister>> registerMap = new ArrayList<Map<String,SysEventRegister>>();
	private EhCacheManager ehcacheCacheManager ;
	/**
	 * 存放事件注册表的缓存服务名称
	 */
	private String cacheName;
	
	ExecutorService executorService = Executors.newFixedThreadPool(50);// 线程池执行器

	@Override
	public void onMessage(final Message message) {
		if (message instanceof ObjectMessage) {

			ObjectMessage objectMessage = (ObjectMessage) message;
			
			try {
				final SysEvent event = (SysEvent)objectMessage.getObject();
				log.debug("received event : "+ event.getName());
				
				Collection<SysEventRegister> registers = SysEventUtil.registerMap.values();
				for(SysEventRegister r : registers){
					
					//如果在注册表中找到注册到的事件注册器，则从线程池中获取一个线程并开启线程
					final SysEventRegister rr = r;
					if(r.getEvent().getName().equals(event.getName())){
						log.debug("have fined event register,event : "+event.getName());
						executorService.submit(new Runnable() {
							@Override
							public void run() {
								rr.getListener().onSysEvent(event);
							}
						});
						
					}
				}
			}  catch (JMSException e) {
				e.printStackTrace();
			}

		}

	}

	public EhCacheManager getEhcacheCacheManager() {
		return ehcacheCacheManager;
	}

	public void setEhcacheCacheManager(EhCacheManager ehcacheCacheManager) {
		this.ehcacheCacheManager = ehcacheCacheManager;
	}

	public String getCacheName() {
		return cacheName;
	}

	public void setCacheName(String cacheName) {
		this.cacheName = cacheName;
	}
}